/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect } from 'react';
import { Upload, Button } from 'antd';
import { FileImageFilled } from '@ant-design/icons';
import request from 'umi-request';
import { debounce } from 'lodash';
import 'braft-editor/dist/index.css';
import 'braft-editor/dist/output.css';
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import type { BuiltInControlType, ExtendControlType } from 'braft-editor';
import styles from './index.less';

interface Props {
  value?: string;
  onChange: Function;
}

const Index = (props: Props) => {
  const { value, onChange } = props;
  const excludeControls: BuiltInControlType[] = ['code', 'emoji', 'media'];

  const hooks = {
    'toggle-link': ({ href, target }: { href: string; target: any }) => {
      href = href.indexOf('http') === 0 ? href : `http://${href}`;
      return { href, target };
    },
    'set-image-link': (href: any) => {
      href = href.indexOf('http') === 0 ? href : `http://${href}`;
      return href;
    },
  };
  const braftUploadFn = (param: any) => {
    if (!param.file) {
      return false;
    }
    const formData = new FormData();
    formData.append('file', param.file);
    request('/Inn/uploadWuLiao', {
      method: 'POST',
      data: formData,
    }).then(({ data }) => {
      if (data) {
        onChange(
          ContentUtils.insertMedias(value, [
            {
              type: 'IMAGE',
              url: data,
              width: '100%',
            },
          ]),
        );
      }
    });
    return;
  };
  const extendControls: ExtendControlType[] = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: (
        <Upload accept='image/*' showUploadList={false} customRequest={braftUploadFn}>
          <Button className='control-item button upload-button' data-title='插入图片'>
            <FileImageFilled />
          </Button>
        </Upload>
      ),
    },
  ];
  const handleChange = debounce(
    (editorState) => {
      onChange(BraftEditor.createEditorState(editorState));
    },
    300,
    {
      leading: true,
      trailing: false,
    },
  );

  useEffect(() => {
    onChange(BraftEditor.createEditorState(value));
  }, [value]);
  return (
    <BraftEditor
      hooks={hooks}
      value={value}
      onChange={handleChange}
      className={styles.braftEditor}
      excludeControls={excludeControls}
      extendControls={extendControls}
      placeholder='请输入通知内容'
    />
  );
};

export default Index;
